export default {
  namespaced: true,
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || []
    // cart: [
    //   {
    //     id: 1,
    //     title: '标题',
    //     img: '图片',
    //     price: 99.99,
    //     amount: 0,
    //     desc: '商品描述信息',
    //     checked: false
    //   }
    // ]
  },
  // 唯一跟新state的地方
  mutations: {
    /**
     *  添加选购商品到购物车
     *  @param state 状态：就是对模块内部state得引用
     *  @param payload 有效载荷，需要外部传递到mutations更新state数据
     */
    addToCart (state, payload) {
    // Array.prototype.some() 判断数组元素是否有元素满足条件
      console.log(payload)
      const has = state.cart.some(prod => prod.id === payload.id)
      // 存在，叠加数量
      if (has) {
        state.cart = state.cart.map(prod => {
          if (prod.id === payload.id) {
            prod.amount += payload.amount
          }
          return prod
        })
      } else {
        state.cart = [
          ...state.cart, // 复制state.cart 数组中的元素到新数组中，浅克隆，=> assign({},obj)
          // JSON.parse(JSON.stringify(obj))  ---深克隆
          payload
        ]
      }
    },
    // 删除购物车商品
    removeCartItem (state, payload) {
      state.cart = state.cart.filter(prod => prod.id !== payload)
      console.log(state.cart)
      // state.cart = state.cart.map((prod, index) => {
      //   if (prod.id === payload) {
      //     state.cart.splice(index, 1)
      //   }
      //   // return state
      // })
    },
    //
    changeCartItemAmount (state, payload) {
      state.cart.map(prod => {
        if (prod.id === payload.id) {
          prod.amount = payload.amount
        }
        return prod
      })
    },
    toggleCartItem (state, payload) {
      state.cart = state.cart.map(prod => {
        if (prod.id === payload) {
          prod.checked = !prod.checked
        }
        return prod
      })
    },
    checkAllCartItem (state, payload) {
      console.log('in all')
      state.cart = state.cart.map(prod => {
        prod.checked = payload
        return prod
      })
    }
  },
  actions: {},
  getters: {
    // 计算总数
    totalCount (state) {
      return state.cart.reduce((sum, curr) => {
        sum += curr.amount
        return sum
      }, 0)
    },
    // 全选
    checkedAll (state) {
      return state.cart.every(prod => prod.checked)
    },
    totalMoney (state) {
      return state.cart.reduce((sum, prod) => {
        if (prod.checked) {
          sum += prod.amount * prod.price
        }
        return sum
      }, 0) * 100
    }
  }
}
